#!/bin/sh

#changelog
: '
* Thurs Apr 14 2022 <shgm@whut.edu.cn> - srcrpm_build-1
- Updated the Copy path of spec and rpm file in docker 

'

# 实现批量的src.rpm到rpm的编译
#Usage: ./srcrpm_build.sh srcrpm_path
# 		build_in_docker.sh需要放到srcrpm_build.sh同目录下！！！！
#		编译结果包含：rpm spec log 存放在success/下


#docker内部的脚本
docker_sh=build_in_docker.sh
#获取当前路径
now_path=$(dirname $(readlink -f $docker_sh))
#rpm编译成功，保存rpm包和spec
success_save=$now_path/success_build	
if [ ! -d $success_save ];then
	mkdir $success_save
fi

#获取系统架构
os_arch=$(arch)

#src.rpm的build的操作
rpm_build()
{

	#获取输入的src rpm路径
	srcrpm_path=$1 
	#echo "$srcrpm_path"
	
	#搜索此目录下所以的src.rpm文件
	srcrpm_files=$(find "$srcrpm_path" -type f -name "*.src.rpm")
	#echo "$srcrpm_files"
	
	#SPECS目录,固定为用户目录下的rpmbuild
	spec_path=/root/rpmbuild/SPECS

	#记录src.rpm的数量
	local num=0 
	
	#RPMS目录,固定为用户目录下的rpmbuild
	rpm_path=/root/rpmbuild/RPMS/${os_arch}

	#SRPMS目录
	srpm_path=/root/rpmbuild/SRPMS
	
	#循环处理每个src.rpm 包括
	#rpm -i src.rpm
	#rpmbuild -ba spec
	for file in $srcrpm_files
	do
		num=$(($num+1))
		cd $now_path
		#获取src.rpm文件名
		echo -e "========= ${num} src rpm start build ========="
		#清除缓存容器
		docker inspect rpm_${num} -f '{{.Name}}' > /dev/null 2>&1
		if [ $? -eq 0 ];then
			if [ docker inspect --format '{{.State.Running}}' rpm_${num} ];then
				docker stop rpm_${num}
			fi
			docker rm -f rpm_${num}
		fi
		
		#启动docker
		docker run -itd --privileged=true --name rpm_${num} openeuler:rpm /usr/sbin/init
		
		#拷贝文件
		docker cp $file rpm_${num}:/root/
		docker cp $docker_sh rpm_${num}:/root/
		
		echo -e "Start $num src rpm build in rpm_${num} container ........."
		#docker内部编译
		docker exec -it rpm_${num} bash -c " chmod a+x /root/build_in_docker.sh "
		
		docker exec -it rpm_${num} bash -c "source /root/build_in_docker.sh"
		

		
		#拷贝结果
		if [ $? -eq 0 ];then
			echo -e "Copy ${file} build spec and rpm ........."
			docker cp rpm_${num}:$spec_path $success_save
			docker cp rpm_${num}:$rpm_path $success_save	
			docker cp rpm_${num}:$srpm_path $success_save
		fi
			
		#删除docker
		echo -e "Stop and Delete rpm_${num} container ........."
		if [ $(docker inspect --format '{{.State.Running}}' rpm_${num}) ];then
			docker stop rpm_${num}
		fi
		docker rm -f rpm_${num}
	done
}

rpm_build "$1" | tee $success_save/src_build.log
